<?php

namespace App\Http\Controllers;

use App\Facades\PaymentConfigFacades;
use App\Facades\PaymentFacades;
use App\Facades\WechatFacades;
use App\Facades\WechatConfigFacades;
use Illuminate\Http\Request;
use App\Helpers\XmlUtil;


class WechatDemoController extends Controller
{
    /**
     * 微信调试入口
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $type = $request->request->get('type');
        /**
         * 微信公众平台配置
         * $config  配置后使用自定义配置，未配置使用系统配置/config/wechat.php
         * $config['appid'];
         * $config['secret'];
         * $config['token']
         * $config['encodingAesKey']
         *
         * WechatConfigFacades::setPublicConfig($config);
         *
         * 微信开放平台配置
         * $config  配置后使用自定义配置，未配置使用系统配置/config/wechat.php
         * $config['componentAppid'];
         * $config['componentSecret'];
         * $config['componentToken']
         * $config['componentEncodingAesKey']
         *
         * WechatConfigFacades::setOpenConfig($config);
         */
        $public_config = [
            'appid' => 'wx9d2993818117bfee',
            'secret' => '56dd5a13a7ffaa83b37ab8fa54b17677',
            'token' => 'TKv477JxjDK9hoZzop4p76Bj9g7xIpss',
            'encodingAesKey' => 'SR6YSTPwUPFsGI1hoGG2pS9BpRaV9PUcaVbthFG6y9X',
        ];

        $open_config = [
            'componentAppid' => 'wx8e742693341062d6',
            'componentSecret' => 'd7bba60e2046b0fd6997d202e14223fb',
            'componentToken' => '5djeuif8wjbgtsyu34jdxnxukdjch955',
            'componentEncodingAesKey' => 'gr2rY491su8i0lBPo1CyXeGOE45kAT75rcAKgx0RaEt',
        ];

        WechatConfigFacades::setPublicConfig();
        WechatConfigFacades::setOpenConfig();

        switch ($type){
            /**
             * 长链接转短链接接口
             */
            case 'shortUrl':
                $result = WechatFacades::getShortUrl('http://www.baidu.com');
                break;
            /**
             * 微信Oauth授权登录
             */
            case 'wechatLogin':
                $result = WechatFacades::wechatLogin('http://mkapi.tunnel.echomod.cn/wechatDemo?type=wechatLogin');
                break;
            /**
             * 生成js 必需的config
             */
            case 'jsApiConfig':
                $result = WechatFacades::jsApiConfig();
                break;
            /**
             * 自定义菜单查询接口(获取菜单)
             */
            case 'getMenu':
                $result = WechatFacades::getMenu();
                break;
            /**
             * 购买成功(付款成功)提醒 (用于会员)
             */
            case 'sendPaySuccessNoticeForBuyer':
                $openid = 'oltsUs2NdBNgta73EEvflMLr5V_Q';
                $data['detail'] = '测试';
                $data['validity_time'] = time();
                $result = WechatFacades::sendPaySuccessNoticeForBuyer($openid,$data);
                break;
            /**
             * 获取微信开放平台预授权码
             */
            case 'getComponentPreAuthCode':
                $force = false;
                $result = WechatFacades::getComponentPreAuthCode($force);
                break;
            /**
             * 获取授权方的公众号帐号基本信息
             */
            case 'getAuthorizerInfo':
                if(empty($request->query->get('auth_code'))){
                    $url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.config('wechat.wechatOpen.componentAppid').'&pre_auth_code='.WechatFacades::getComponentPreAuthCode().'&redirect_uri='.urlencode('http://mkapi.tunnel.echomod.cn/wechatDemo?type=getAuthorizerInfo');
                    echo "<button onclick=\"window.location.href='".$url."'\"><span>我有微信公众号，立即绑定</span></button>";
                    exit;
                }

                $authCode=$request->query->get('auth_code');
                $authInfo = WechatFacades::getComponentAuthInfo($authCode);

                $result = WechatFacades::getAuthorizerInfo($authInfo['authorization_info']);
                break;
            /**
             * 获取微信开放平台授权信息
             */
            case 'getComponentAuthInfo'://
                if(empty($request->query->get('auth_code'))){
                    $url = 'https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid='.config('wechat.wechatOpen.componentAppid').'&pre_auth_code='.WechatFacades::getComponentPreAuthCode().'&redirect_uri='.urlencode('http://mkapi.tunnel.echomod.cn/wechatDemo?type=getAuthorizerInfo');
                    echo "<button onclick=\"window.location.href='".$url."'\"><span>我有微信公众号，立即绑定</span></button>";
                    exit;
                }

                $authCode=$request->query->get('auth_code');
                $result = WechatFacades::getComponentAuthInfo($authCode);
                break;
            default:
                $result = WechatFacades::getShortUrl('http://www.baidu.com');
        }

        return response()->json([
            'status' => 'success',
            'status_code' => 200,
            'data' => $result
        ],200);
    }

    /**
     * 支付调试入口
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function pay(Request $request)
    {
        $type = $request->request->get('type');
        /**
         * 支付配置
         * $config  配置后使用自定义配置，未配置使用系统配置/config/payment.php
         *
         * type 支付方式    wechatNative:原生微信支付 wechatSub:子商户微信支付 zhongxinPay:中信支付
         *
         * 原生微信支付配置
         * $config['type'] = 'wechatNative';
         * $config['appid'];
         * $config['mchid'];
         * $config['key']
         * $config['appSecret']
         * $config['is_sub_pay']
         *
         * 子商户微信支付配置
         * $config['type'] = 'wechatSub';
         * $config['sub_appid']
         * $config['sub_mchid']
         * $config['sub_key']
         * $config['sub_appSecret']
         * $config['parent_appid']
         * $config['parent_appSecret']
         * $config['parent_mchid']
         * $config['parent_key']
         * $config['parent_key']
         *
         * PaymentFacades::setPaymentConfig($config);
         */
        $wechatPay_config = [
            'wechatPay' => [
                //原生
                'appid' => 'wxe56ac9c9906ca376',//美食魔卡 openId:oDc1s05I4pN0r4mxuhPnaJ4wcRdQ
                'mchid' => '1483744372',
                'key' => 'bXrNwuKuoLB3g90DrFChZImZox5gkQNa',
                'appSecret' => '37eb2127a81b31279c35752f95ff1de2',
                //子商户
                'sub_appid' => 'wxac8100cc853c1274',//魔力值钱包 openId:oywvQ0wbmVP893LlxVT43_QT2kJo
                'sub_mchid' => '1497033182',
                'sub_key' => 'aD0zWjsEFmCqkv91PlnQrMe9COZ2iHSL',
                'sub_appSecret' => '3abe035d1601a0ec9d65e95870190b0b',
                'parent_appid'       => 'wxaeb386622e4fefe1',//服务商支付公众号的APPID(聚宝盆网络)
                'parent_appSecret'       => 'aaecca2b266b25687438580351041d68',//服务商支付公众号的appSecret
                'parent_mchid'       => '1420210002',//服务商支付商户号
                'parent_key'       => 'LCBYDyPGP3p8pF2D1S65vY1ydx4Yas4q',//服务商商户支付密钥
                'is_sub_pay'       => true,
            ]
        ];

        $zhongxinPay_config = [
            'zhongxinPay' => [
                'appid' => 'wx20212486beac60cf',
                'mchId' => '399560668480',
                'key' => '3412369a8d85f2671bfbc32870a619c9',
                'public_rsa_key' => '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqNxzebovJ6R+LF0jFyJD4vgdvj+Apmb5h+pW3T0EtDzWZAr7tyiSAtNedYvRjJCqN5cYw0rIwGMZFbD3lQHbJGC+IvpqXwPB8AWqRAwItI82fo2+AyHkq11yE27IgOjSrKofgg3GWJ6SSQonYuXZ0c09chXXiZPKYe0zRbvq83kAVsYDu1sMwi8mfiVff6CIALsehs1MOjmdLW40N1CicVmJaWuh2yee+sj1/0xMOlV1LyJq63hShBD7T93qpGbHoNkpdz+BFc2byrhv1idbB4DRbUiKynzj3FX2Nz8Dv9TFQv8p2Z8dIOst890atv3P8DO7a9FI8I1reLvFDdyPawIDAQAB
-----END PUBLIC KEY-----',
                'private_rsa_key' => '-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDWlTCouyDHEwXfiN71jIRQy2mcAz/dM+eyiHrYQHP1bJIoRYTm
Kn2yoJA7+YZkk063Ydy/UeI4rjdbZBrkoQWeBG4skciFL4ICdGhZJGeCwB+92jXi
BR0ZamBG+fbC3hW1Wje8jXNZ3RDVTnCPuW2rjg/pTl3JbB3ybIhCDQAmnQIDAQAB
AoGBAMXsbCpmF/CnQjaRx51Tk8P2K55EfQaqVp8dNbn7kTmhgBp3LQMj1DcL1J4N
JQHlwahyMquhenjvcI3ygr+5KjSKdSHlI2sVsOXZIVD2tGhf+9m+PDMZTo2Ay6mu
xrwrYQxMjZhMyEt2jVXVcaJ3SZPuqBVxY+08IMrx4TuRqsBhAkEA9O/lSHQExZT6
tuJ+m3yRQ0r/kL0rbiWNoW4DE7buUU+CsbKRrbicvqhqJpPTvKY7xW0LeghaMZEI
I1Q6wpfW2QJBAOBGUfubxnoLVnFnGU9Ntx2EicxhC/o05QowjjIp6h0pGClnVBZN
lMtDcykm5LLU+8C9/KQfB4OR3H+N3PQ7m2UCQFB5MP+o/phb5jOIHsi/GIrfbTAE
tuwtcmcDWgd0JsCYOvxfCvXknbsWYinij8J/a0vmE8s4S0nVuLLCzbt5X6ECQQC2
/KkngZIPQfDl1hjwe5hMnTdRal07aKz4A2YBx/Ecmcr8/TG+gM5GimIL0ZAH2X8P
Y/QedLLMxtYBvN3q6DeBAkA+8uXiuLsfPASYwNt/5ZHPxdR7d5d7npZFkcuU8U4L
fpTCXyx2pB3wC4Vzy0k0zIDTSiQviw/X9OwPyFNa3/4f
-----END RSA PRIVATE KEY-----',
                'debug' => false,
            ]
        ];

        PaymentConfigFacades::setPaymentConfig();

        switch ($type){
            /**
             * 微信JSAPI支付
             */
            case 'wechatJsapiPay':
                $data['pay_type'] = 2;

                $data['body'] = '测试 精美礼品';//商品描述
                $data['product_id'] = 1;//商品id
                $data['trade_type'] = 'JSAPI';
                $data['out_trade_no'] = 'J'.time().random_int(0000,9999);//商户订单号
                $data['total_fee'] = 1;//总金额
                $data['notify_url'] = 'http://mkapi.tunnel.echomod.cn/paynotify';//异步通知地址,不能携带任何参数
                $data['openId'] = 'ofWDcwVH58VBE7Xe5qHEUtSrfDXU';//聚宝盆科技
                //$data['openId'] = 'oDc1s05I4pN0r4mxuhPnaJ4wcRdQ';//美食魔卡
                //$data['subOpenid'] = 'o0-K-0ipnag6DHBU0kygNfHGksjY';//子商户必传(魔力魔力)
                $data['subOpenid'] = 'oywvQ0wbmVP893LlxVT43_QT2kJo';//子商户必传(魔力值钱包)
                $data['attach'] = '1:5';//附加数据
                $result = PaymentFacades::pay($data);
                break;
            /**
             * 微信扫码支付
             */
            case 'wechatNativePay':
                $data['pay_type'] = 1;

                $data['body'] = '测试 扫码精美礼品';//商品描述
                $data['product_id'] = 1;//商品id
                $data['trade_type'] = 'NATIVE';
                $data['out_trade_no'] = 'S'.time().random_int(0000,9999);//商户订单号
                $data['total_fee'] = 1;//总金额
                $data['notify_url'] = 'http://mkapi.tunnel.echomod.cn/paynotify';//异步通知地址,不能携带任何参数
                $data['attach'] = '1:5';//附加数据
                $result = PaymentFacades::pay($data);
                break;
            /**
             * 微信查询订单
             */
            case 'wechatOrderQuery':
                $data['out_trade_no'] = '15324030165613';//商家流水号
                $data['transaction_id'] = '';//微信交易号

                $result = PaymentFacades::orderQuery($data);
                break;
            /**
             * 微信退款
             */
            case 'wechatRefundOrder':
                $data['out_trade_no'] = '15324030165613';//原订单商家流水号
                $data['transaction_id'] = '';//原订单微信交易号
                $data['total_fee'] = '1';//原订单金额
                $data['refund_fee'] = '1';//退款金额
                $data['refund_no'] = 'R'.time().random_int(0000,9999);//退款单号
                $data['notify_url'] = '';//异步回调地址

                $result = PaymentFacades::refund($data);
                break;
            /**
             * 企业付款到零钱
             */
            case 'wechatChangePay':
                $data['check_name'] = 'NO_CHECK';//不校验真实姓名
                $data['total_fee'] = '100';//金额
                $data['openid'] = 'ofWDcwVH58VBE7Xe5qHEUtSrfDXU';//openid
                $data['partner_trade_no'] = 'P'.time().random_int(0000,9999);//商家流水号
                $data['desc'] = '测试';//描述

                $result = PaymentFacades::changePay($data);
                break;
            default:
                $result = PaymentFacades::pay();
        }


        return response()->json([
            'status' => 'success',
            'status_code' => 200,
            'data' => $result
        ],200);
    }

    /**
     * 开放平台访问入口
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function wechatapi(Request $request)
    {
        WechatConfigFacades::setOpenConfig();
        $data = WechatFacades::main();

        return response()->json([
            'status' => 'success',
            'status_code' => 200,
            'data' => $data
        ],200);
    }

    /**
     * 支付回调
     *
     * @param Request $request
     * @throws \App\Services\Payment\PayCore\wechat\lib\WxPayException
     */
    public function payNotify(Request $request)
    {
        $xml = $request->getContent();

        $xmlArr=[];
        if($xml){
            //判断字符串是否xml
            if(!XmlUtil::xml_parser($xml)){
                $xmlArr = XmlUtil::paramsToArray($xml);
            }else{
                $xmlArr=XmlUtil::FromXml($xml);
            }
        }

        if(isset($xmlArr["transaction_id"])){
            $paymentService = PaymentFacades::getPaymentObject('wechatPay');
            $res = $paymentService->notify($request);
        }elseif(isset($xmlArr["out_transaction_id"])){
            $paymentService = PaymentFacades::getPaymentObject('zhongxinPay');
            $res = ['code'=>0,'data'=>[]];
        }elseif(isset($xmlArr["req_info"]) && isset($xmlArr["appid"])){//微信退款异步通知
            $paymentService = PaymentFacades::getPaymentObject('wechatPay');
            $res = $paymentService->refundNotify($request);
        }

        if(empty($res['code'])){
            print_r('支付成功');exit;
        }else{
            print_r('支付失败');exit;
        }
    }
}
